package secondriver.heathfood.activity;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ScrollView;
import android.widget.Toast;
import secondriver.heathfood.HeathFoodApplication;
import secondriver.heathfood.R;
import secondriver.heathfood.bean.ApkInfoEntity;
import secondriver.heathfood.common.BackgroundTaskExecutor;
import secondriver.heathfood.common.BackgroundTasks;
import secondriver.heathfood.service.UpgradeService;
import secondriver.heathfood.util.*;
import secondriver.heathfood.util.unused.SimpleSQLiteHelper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Author : secondriver
 * Date :  2015/10/19
 */
public abstract class AbstractBaseActivity extends Activity {

    public final SimpleSQLiteHelper sqliteHelper = HeathFoodApplication.getSQLiteHelper();

    private final LogUtil logUtil = LogUtil.getLogger(AbstractBaseActivity.class.getName());

    public final void enableHomeButton() {
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setDisplayShowHomeEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }

    public final void setActionBarTitle(int titleResId) {
        enableHomeButton();
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setTitle(titleResId);
        }
    }

    public final void setActionBarTitle(String title) {
        enableHomeButton();
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setTitle(title);
        }
    }

    protected final int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater menuInflater = new MenuInflater(this);
        menuInflater.inflate(R.menu.sys_menu, menu);
        menu.findItem(R.id.menu_item_food_favorites).setVisible(false);
        menu.findItem(R.id.menu_item_screen_shot_save).setVisible(false);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        MenuItem menuItem = menu.findItem(R.id.menu_item_clear_cache);
        menuItem.setVisible(true);
        menuItem.setTitle(getString(R.string.clear_cache, SimpleDiskCache.getCacheSize(this)));
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.menu_item_food_favorites:
                break;
            case R.id.menu_item_screen_shot_save:
                handlerScreenShotShare(item);
                break;
            case R.id.menu_item_clear_cache:
                handlerClearCache(item);
                break;
            case R.id.menu_item_about:
                handlerAbout(item);
                break;
            case R.id.menu_item_update:
                handlerUpdate(item);
                break;
            case R.id.menu_item_exit:
                handlerExit(item);
                break;
            default:
        }
        return true;
    }

    public void handlerScreenShotShare(MenuItem menuItem) {
        if (FileUtil.isUsableExternalStorage()) {
            File heathPictureDir = FileUtil.createAppExternalPublicPictureDirectory();
            if (null != heathPictureDir && heathPictureDir.exists()) {
                Bitmap bitmap = screenShotScrollView();
                File filePath = new File(heathPictureDir, FileUtil.generatorScreenShotPictureName());
                boolean flag = false;
                if (!filePath.exists()) {
                    try {
                        flag = filePath.createNewFile();
                    } catch (IOException e) {
                        logUtil.error(filePath + " create failed .", e);
                    }
                }
                if (flag && null != bitmap && saveBitmap(bitmap, filePath)) {
                    showSimpleToast(R.string.info_screen_shot_succeed);
                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri mediaUri = Uri.fromFile(filePath);
                    mediaScanIntent.setData(mediaUri);
                    this.sendBroadcast(mediaScanIntent);
                    //分享
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, mediaUri);
                    shareIntent.setType("image/*");
                    startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share)));
                } else {
                    showSimpleToast(R.string.info_screen_shot_fail);
                }
            } else {
                showSimpleToast(R.string.info_create_directory_fail);
            }
        } else {
            showSimpleToast(R.string.info_sdcard_note_available);
        }
    }

    public void handlerClearCache(MenuItem menuItem) {
        SimpleDiskCache.clearCache(this);
        Toast.makeText(this, R.string.info_clear_cache, Toast.LENGTH_LONG).show();
    }

    public void handlerAbout(MenuItem menuItem) {
        String message = getString(R.string.info_about,
                HeathFoodApplication.getVersionName(), getString(R.string.app_author), getString(R
                        .string.app_created));
        new AlertDialog.Builder(this)
                .setTitle(getString(R.string.app_name))
                .setCancelable(true)
                .setMessage(message)
                .show();
    }

    public void handlerUpdate(MenuItem menuItem) {
        if (HeathFoodApplication.isNetworkAvailable()) {
            checkAppVersion();
        } else {
            showSimpleToast(R.string.info_network_not_available);
        }
    }

    public void handlerExit(MenuItem menuItem) {
        new AlertDialog.Builder(this)
                .setTitle(R.string.exit)
                .setMessage(R.string.info_exit)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setCancelable(false)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        HeathFoodApplication.ActivityCollector.finishAllActivity();
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
    }

    public Bitmap screenShotScrollView() {
        return null;
    }

    public final Bitmap screenShot(ScrollView scrollView) {
        if (null == scrollView) {
            throw new IllegalArgumentException("parameter can't be null.");
        }
        int height = 0;
        Bitmap bitmap;
        for (int i = 0, s = scrollView.getChildCount(); i < s; i++) {
            height += scrollView.getChildAt(i).getHeight();
            scrollView.getChildAt(i).setBackgroundResource(android.R.drawable.screen_background_light);
        }
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), height, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);
        return bitmap;
    }

    public final Bitmap screenShot(View view) {
        if (null == view) {
            throw new IllegalArgumentException("parameter can't be null.");
        }
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    public final Bitmap screenShot(Activity activity) {
        if (null == activity) {
            throw new IllegalArgumentException("parameter can't be null.");
        }
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();

        Bitmap b1 = view.getDrawingCache();
        Rect frame = new Rect();
        view.getWindowVisibleDisplayFrame(frame);

        int statusBarHeight = frame.top;

        Point point = new Point();
        activity.getWindowManager().getDefaultDisplay().getSize(point);

        int width = point.x;
        int height = point.y;

        Bitmap b2 = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return b2;
    }

    private final boolean saveBitmap(Bitmap bitmap, File filePath) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            if (fos != null) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                return true;
            }
        } catch (FileNotFoundException e) {
            logUtil.error(filePath + " not found .", e);
        } catch (IOException e) {
            logUtil.error("bitmap save occur exception.", e);
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    logUtil.error("close FileOutputStream exception.", e);
                }
            }
        }
        return false;
    }

    protected void showSimpleToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    protected void showSimpleToast(int resId) {
        Toast.makeText(this, getString(resId), Toast.LENGTH_LONG).show();
    }

    private static final int GET_APP_VERSION_WHAT = 1;

    private Handler upgradeHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_APP_VERSION_WHAT:
                    Boolean rs = (Boolean) msg.obj;
                    if (rs) {
                        String apkInfoJson = FileUtil.readFromFile(ApkInfoEntity.APK_INFO_FILE_NAME, AbstractBaseActivity
                                .this);
                        final ApkInfoEntity apkInfoEntity = ApkInfoEntity.builder(apkInfoJson);
                        upgradeApp(apkInfoEntity);
                    } else {
                    }
                    break;
                default:
                    break;
            }
        }
    };


    protected final void checkAppVersion() {
        if (FileUtil.fileIsExist(ApkInfoEntity.APK_INFO_FILE_NAME, this)) {
            String json = FileUtil.readFromFile(ApkInfoEntity.APK_INFO_FILE_NAME, this);
            final ApkInfoEntity apkInfoEntity = ApkInfoEntity.builder(json);
            upgradeApp(apkInfoEntity);
            FileUtil.deleteFile(ApkInfoEntity.APK_INFO_FILE_NAME, this);
        } else {
            Message message = Message.obtain(upgradeHandler, GET_APP_VERSION_WHAT);
            BackgroundTaskExecutor.doTask(null, message, new BackgroundTasks.PullAppVersionInfoTask(this));
        }
    }

    private final void upgradeApp(final ApkInfoEntity apkInfoEntity) {
        final Context context = this;
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.info_app_update).setIcon(android.R.drawable.ic_dialog_info);
        if (apkInfoEntity.versionCode > HeathFoodApplication.getVersionCode()) {
            builder.setMessage(getString(R.string.info_version_update, apkInfoEntity.versionName,
                    HeathFoodApplication.getVersionName()))
                    .setPositiveButton(R.string.update, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(UpgradeService.ACTION_UPGRADE_SERVICE);
                            intent.setPackage(context.getPackageName());
                            intent.putExtra(ApkInfoEntity.APK_INFO_KEY, apkInfoEntity);
                            startService(intent);
                        }
                    })
                    .setNegativeButton(R.string.next, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
        } else {
            builder.setMessage(R.string.info_already_new_version)
                    .setCancelable(true)
                    .show();
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        HeathFoodApplication.ActivityCollector.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HeathFoodApplication.ActivityCollector.removeActivity(this);
    }
}